package com.infrastructure.net;

import com.infrastructure.activity.BaseActivity;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by zyt on 16/6/14 11:37 .
 * Email : syy19930112@aliyun.com
 * Description:
 * <p>
 * 用于取消请求(cancelRequest).<br>
 * 每次发起请求,都会把为此创建的{@link HttpRequest}对象放在{@link RequestManager}对象中,所以{@link RequestManager}保存了所有的request.
 * </p>
 */
public class RequestManager {
    ArrayList<HttpRequest> requestList = null;

    public RequestManager(final BaseActivity activity) {
        // 异步请求列表
        requestList = new ArrayList<>();
    }

    /**
     * 添加Request到列表
     */
    public void addRequest(final HttpRequest request) {
        requestList.add(request);
    }

    /**
     * 不管三七二十一取消所有的网络请求
     */
    public void cancelRequest() {
        if ((requestList != null) && (requestList.size() > 0)) {
            for (final HttpRequest request : requestList) {
                if (request.getCall() != null) {
                    try {
                        request.getCall().cancel();//取消请求
                        // TODO 不懂
                        requestList.remove(request);//从集合中移除
                    } catch (final UnsupportedOperationException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 无参数调用
     */
    public HttpRequest createRequest(final URLData urlData,
                                     final RequestCallback requestCallback) {
        return createRequest(urlData, null, requestCallback);
    }

    /**
     * 有参数调用
     */
    public HttpRequest createRequest(final URLData urlData,
                                     final List<RequestParameter> params,
                                     final RequestCallback requestCallback) {
        final HttpRequest request = new HttpRequest(urlData, params,
                requestCallback);
        addRequest(request);
        return request;
    }
}
